// NewScenarioState.cpp: implementation of the NewScenarioState class.
//
//////////////////////////////////////////////////////////////////////

#include "NewScenarioState.h"
#include "ScenarioCreationState.h"

#ifdef FREEGLUT_IS_PRESENT
#  include <GL/freeglut.h>
#else
#  ifdef __APPLE__
#    include <GLUT/glut.h>
#  else
#    include <GL/glut.h>
#  endif
#endif

/* PLIB includes */
#include <plib/ul.h>
#include <plib/pu.h>
#include <plib/puAux.h>
#include <plib/fnt.h>

#include "LoadingInfo.h"
#include "BackGroundImage.h"
#include "ImageButton.h"
#include "VideoImage.h"
#include "ProgressBar.h"
#include "Keyboard.h"
#include "Joystick.h"
#include "Mouse.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

NewScenarioState::NewScenarioState()
{
this->oldState = NULL;
shouldDeleteNextState = FALSE;
this->nextState = NULL;
this->load("");
}

NewScenarioState::NewScenarioState(State* oldState)
{
this->oldState = oldState;
shouldDeleteNextState = FALSE;
this->nextState = NULL;
this->load("");
}

NewScenarioState::~NewScenarioState()
{
delete backgroundImage;
delete backButton;
delete backDisabledButton;
delete cancelButton;
delete cancelDisabledButton;
delete ms;
delete kb;
}

void NewScenarioState::load(const char* filename)
{
// Must be initialized but only here works well!!!
// Use a different critical section for each state where needed
//InitializeCriticalSection(&criticalSection);
progress = 0.0f;

int h = (float)glutGet ( (GLenum) GLUT_WINDOW_HEIGHT ) ;
int w = (float)glutGet ( (GLenum) GLUT_WINDOW_WIDTH  ) ;
    
this->backgroundImage = new BackGroundImage("./NewScenarioState.bmp");

                                      
backButton = new ImageButton("./backNormal.bmp",
                             "./backFocused.bmp",
                             "./backClicked.bmp",
                             eAlphaKey_RED,
                             0.24f,0.01f,0.15f,0.1f);
backDisabledButton = new ImageButton("./backDisabled.bmp",
                             "./backDisabled.bmp",
                             "./backDisabled.bmp",
                             eAlphaKey_RED,
                             0.24f,0.01f,0.15f,0.1f);
cancelButton = new ImageButton("./cancelNormal.bmp",
                             "./cancelFocused.bmp",
                             "./cancelClicked.bmp",
                             eAlphaKey_RED,
                             0.61f,0.01f,0.16f,0.1f);
cancelDisabledButton = new ImageButton("./cancelDisabled.bmp",
                             "./cancelDisabled.bmp",
                             "./cancelDisabled.bmp",
                             eAlphaKey_RED,
                             0.61f,0.01f,0.16f,0.1f);

loadButton = new ImageButton("./loadNormal.bmp",
                             "./loadFocused.bmp",
                             "./loadClicked.bmp",
                             eAlphaKey_RED,
                             0.40f,0.10f,0.20f,0.10f);

loadingImage = new VideoImage("./Loading1.bmp",
                             "./Loading2.bmp",
                             "./Loading3.bmp",
                             eAlphaKey_RED,
                             0.30f,0.15f,0.40f,0.2f,0.4f);

cancelingImage = new VideoImage("./Canceling1.bmp",
                             "./Canceling2.bmp",
                             "./Canceling3.bmp",
                             eAlphaKey_RED,
                             0.30f,0.15f,0.40f,0.2f,0.4f);

scenarioProgressBar = new ProgressBar(0.6f,0.62f,0.25f,0.04f,8,PB_COLOR_SUNBURST);
mapProgressBar      = new ProgressBar(0.6f,0.51f,0.25f,0.04f,8,PB_COLOR_SUNBURST);
textureProgressBar  = new ProgressBar(0.6f,0.4f, 0.25f,0.04f,8,PB_COLOR_SUNBURST);

createPUI(w,h);

/* Other stuff */
this->kb = new Keyboard();
this->ms = new Mouse();
                             
backButtonEnabled = true;
cancelButtonEnabled = false;

nextState = this;
innerState = NEW_SCENARIO_SELECTION; 
lc = FALSE;

// function used to communucation between threads
this->info.completed = false;
this->info.mapProgress = 0.0f;
this->info.objectsProgress = 0.0f;
this->info.scenarioProgress = 0.0f;
this->info.texturesProgress = 0.0f;
this->info.canceled = false;
this->info.doneCanceling = false;
}

void NewScenarioState::createPUI(int w, int h)
{
/* FONT creation */
fnt = new fntTexFont( "./DEFAULT.txf" );
font = new puFont(PUFONT_HELVETICA_18);
tex_font = new puFont( fnt, 18.0f, 0 );

/* PUI default settings */
//puSetDefaultFonts        ( *tex_font, *font );
puSetDefaultStyle        ( PUSTYLE_SMALL_SHADED ) ;
puSetDefaultColourScheme ( COLOR_ICE ) ;

progress_group = new puGroup(0,0);

sprintf(scenario_progress_label,"SCENARIO CREATION PROGRESS");
scenario_progress_text = new puText(0.21f * w, 0.62f * h);
scenario_progress_text -> setLabel(scenario_progress_label);
scenario_progress_text -> setColor(PUCOL_LABEL,COLOR_SUNBURST);
scenario_progress_text -> setLabelFont(*font);

sprintf(map_progress_label,"MAP CREATION PROGRESS");
map_progress_text = new puText(0.21f * w, 0.51f * h);
map_progress_text -> setLabel(map_progress_label);
map_progress_text -> setColor(PUCOL_LABEL,COLOR_SUNBURST);
map_progress_text -> setLabelFont(*font);

sprintf(texture_progress_label,"TEXTURE CREATION PROGRESS");
texture_progress_text = new puText(0.21f * w, 0.40f * h);
texture_progress_text -> setLabel(texture_progress_label);
texture_progress_text -> setColor(PUCOL_LABEL,COLOR_SUNBURST);
texture_progress_text -> setLabelFont(*font);

progress_group->close();
progress_group->hide();

browse_group = new puGroup(0,0);

/* PUI widgets' settings */
sprintf(info_label,INFO_STRING);
info_text = new puText(0.11f * w, 0.68f * h);
info_text -> setLabel(info_label);
info_text -> setColor(PUCOL_LABEL,COLOR_SUNBURST);

sprintf(dem_file,"Choose a scenario (.DEM) file");
demFileText = new puFrame (0.11f * w, 0.58f * h, 0.8f * w, 0.62f * h);
demFileText -> setLegend(dem_file);
demFileText -> setColor(PUCOL_LEGEND,COLOR_WHITE);

sprintf(map_file,"Choose a map (.BMP) file");
mapFileText = new puFrame (0.11f * w, 0.48f * h, 0.8f * w, 0.52f * h);
mapFileText -> setLegend(map_file);
mapFileText -> setColor(PUCOL_LEGEND,COLOR_WHITE);

sprintf(tex_file,"Choose a textures (.BMP) file");
texFileText = new puFrame (0.11f * w, 0.38f * h, 0.8f * w, 0.42f * h);
texFileText -> setLegend(tex_file);
texFileText -> setColor(PUCOL_LEGEND,COLOR_WHITE);

sprintf(obj_file,"Choose a objects (.BMP) file");
objFileText = new puFrame (0.11f * w, 0.28f * h, 0.8f * w, 0.32f * h);
objFileText -> setLegend(obj_file);
objFileText -> setColor(PUCOL_LEGEND,COLOR_WHITE);


demFileBrowse = new puOneShot(0.81f * w,0.58f * h,"Browse");
demFileBrowse -> setCallback(browse_dem);
demFileBrowse -> setUserData(this);
demFileBrowse -> setColor(PUCOL_BACKGROUND,COLOR_RED);
demFileBrowse -> setColor(PUCOL_FOREGROUND,COLOR_SUNBURST);
demFileBrowse -> setColor(PUCOL_HIGHLIGHT,COLOR_SUNBURST);
demFileBrowse -> setColor(PUCOL_LABEL, COLOR_WHITE);
demFileBrowse -> setColor(PUCOL_LEGEND, COLOR_WHITE);

mapFileBrowse = new puOneShot(0.81f * w,0.48f * h,"Browse");
mapFileBrowse -> setCallback(browse_map);
mapFileBrowse -> setUserData(this);
mapFileBrowse -> setColor(PUCOL_BACKGROUND,COLOR_RED);
mapFileBrowse -> setColor(PUCOL_FOREGROUND,COLOR_SUNBURST);
mapFileBrowse -> setColor(PUCOL_HIGHLIGHT,COLOR_SUNBURST);
mapFileBrowse -> setColor(PUCOL_LABEL, COLOR_WHITE);
mapFileBrowse -> setColor(PUCOL_LEGEND, COLOR_WHITE);

texFileBrowse = new puOneShot(0.81f * w,0.38f * h,"Browse");
texFileBrowse -> setCallback(browse_tex);
texFileBrowse -> setUserData(this);
texFileBrowse -> setColor(PUCOL_BACKGROUND,COLOR_RED);
texFileBrowse -> setColor(PUCOL_FOREGROUND,COLOR_SUNBURST);
texFileBrowse -> setColor(PUCOL_HIGHLIGHT,COLOR_SUNBURST);
texFileBrowse -> setColor(PUCOL_LABEL, COLOR_WHITE);
texFileBrowse -> setColor(PUCOL_LEGEND, COLOR_WHITE);

objFileBrowse = new puOneShot(0.81f * w,0.28f * h,"Browse");
objFileBrowse -> setCallback(browse_obj);
objFileBrowse -> setUserData(this);
objFileBrowse -> setColor(PUCOL_BACKGROUND,COLOR_RED);
objFileBrowse -> setColor(PUCOL_FOREGROUND,COLOR_SUNBURST);
objFileBrowse -> setColor(PUCOL_HIGHLIGHT,COLOR_SUNBURST);
objFileBrowse -> setColor(PUCOL_LABEL, COLOR_WHITE);
objFileBrowse -> setColor(PUCOL_LEGEND, COLOR_WHITE);

browse_group -> close();
}

void NewScenarioState::reset()
{
//this->nextState = this;

backButtonEnabled = true;
cancelButtonEnabled = false;

//nextState = this;
innerState = NEW_SCENARIO_SELECTION; 

cancelButton->reset();
cancelDisabledButton->reset();
backButton->reset();
backDisabledButton->reset();
loadButton->reset();

this->cancelButtonEnabled = FALSE;
this->backButtonEnabled = TRUE;

lc = FALSE;

browse_group->hide();
progress_group->hide();

info.canceled = FALSE;
info.completed = FALSE;
info.old_s = this;
info.doneCanceling = FALSE;
}

void NewScenarioState::display(void)
{
// background image, always displayed
backgroundImage->display();

// those buttons should always be displayed
if (cancelButtonEnabled) cancelButton->display();
else cancelDisabledButton->display();
if (backButtonEnabled) backButton->display();
else backDisabledButton->display();

   
if(innerState == NEW_SCENARIO_SELECTION)
         {
         // show PUI widgets	 
         }
else if(innerState == NEW_SCENARIO_SELECTED)
		{
         // show load buttons
         loadButton->display();	     
		}
else if(innerState == NEW_SCENARIO_LOADING)
		{
         // show loading image
         loadingImage->display();
         
         float sp;
         float mp;
         float tp;
         
         // copy the values to leave the critical section quickly
        // try
           // {
            // EnterCriticalSection(&criticalSection);
             sp = info.scenarioProgress;
             mp = info.mapProgress;
             tp = info.texturesProgress;
			 lc = info.completed;
            // LeaveCriticalSection(&criticalSection);
            // }
        // catch(...)
            // {
            // LeaveCriticalSection(&criticalSection);
            // }
         // show progress bars
         scenarioProgressBar->display(sp);
         mapProgressBar->display(mp);
         textureProgressBar->display(tp);
         }
else if(innerState == NEW_SCENARIO_CANCELING)
         {
         bool dc = false;
         cancelingImage->display();
        // try
          //  {
           //  EnterCriticalSection(&criticalSection);
             dc = info.doneCanceling;
            // LeaveCriticalSection(&criticalSection);
            // }
        // catch(...)
            // {
            // LeaveCriticalSection(&criticalSection);
            // }
         if(dc) 
             {
             innerState = NEW_SCENARIO_SELECTION;
             info.doneCanceling = false;
             info.canceled = false;
             info.completed = false;
             backButtonEnabled = true;
             cancelButtonEnabled = false;
			 browse_group -> reveal();
             }
         }

// Display PUI  
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glAlphaFunc(GL_GREATER,0.1f);
puDisplay();
}

void NewScenarioState::resize(int w, int h)
{

}

void NewScenarioState::reopen()
{
backButtonEnabled = true;
cancelButtonEnabled = false;

nextState = this;
innerState = NEW_SCENARIO_SELECTION; 

cancelButton->reset();
cancelDisabledButton->reset();
backButton->reset();
backDisabledButton->reset();
loadButton->reset();

this->cancelButtonEnabled = FALSE;
this->backButtonEnabled = TRUE;

lc = FALSE;

browse_group->reveal();
}

void NewScenarioState::keyUp(unsigned char key, int x, int y)
{
kb->read(key,GLUT_UP,x,y);
}

void NewScenarioState::keyDown(unsigned char key, int x, int y)
{
kb->read(key,GLUT_DOWN,x,y);
}

void NewScenarioState::specialUp(int key, int x, int y)
{
kb->read(key,GLUT_UP,x,y);
}

void NewScenarioState::specialDown(int key, int x, int y)
{
kb->read(key,GLUT_DOWN,x,y);
}


void NewScenarioState::motion(int newx, int newy)
{
puMouse(newx,newy); 
}

void NewScenarioState::passive(int newx, int newy)
{
if(backButtonEnabled) backButton->mouse(-1,-1,newx,newy);
else backDisabledButton->mouse(-1,-1,newx,newy);
if (cancelButtonEnabled) cancelButton->mouse(-1,-1,newx,newy);
else cancelDisabledButton->mouse(-1,-1,newx,newy);
loadButton->mouse(-1,-1,newx,newy);
puMouse(-1,-1,newx,newy);
}

void NewScenarioState::mouse(int button, int state, int mouseX, int mouseY)
{
puMouse(button,state,mouseX,mouseY);
  
if(innerState == NEW_SCENARIO_SELECTED)
{

if(loadButton->mouse(button,state,mouseX,mouseY))
     {
     backButtonEnabled = false;
     cancelButtonEnabled = true;
     innerState = NEW_SCENARIO_LOADING;     
     progress_group -> reveal();
	 browse_group -> hide();
     //info.cs = &criticalSection;
	 info.old_s = this;
	 info.cnt = ssgGetCurrentContext();
	 strcpy(info.dem_filename,this->dem_file);
	 strcpy(info.obj_filename,this->obj_file);
	 strcpy(info.tex_filename,this->tex_file);
	 strcpy(info.map_filename,this->map_file);
	 strcpy(info.wpn_filename,this->wpn_file);
	 strcpy(info.cmv_filename,this->cmv_file);
	 loadTextures(&info);
	 info.h = (float)glutGet ( (GLenum) GLUT_WINDOW_HEIGHT );
	 info.w = (float)glutGet ( (GLenum) GLUT_WINDOW_WIDTH );
	 info.loadingType = CREATE;
	 //ScenarioCreationState *scs = new ScenarioCreationState(this,&info,NEWSCENARIO);
     // start thread
     /*hThread = (HANDLE) _beginthreadex(NULL,0,loadNewScenario,&info,0,(unsigned int *)&dwThreadId);
     // Check the return value for success. 
	 if (hThread == NULL)
		{
        exit(0);
	    }*/
     }
}     

if(backButtonEnabled) 
     { 
     if(backButton->mouse(button,state,mouseX,mouseY)) 
           this->nextState = this->oldState;
     }
if(cancelButtonEnabled) 
     { 
     if(cancelButton->mouse(button,state,mouseX,mouseY))
           {
           // cancel operation
           backButtonEnabled = false;
           cancelButtonEnabled = false;
           innerState = NEW_SCENARIO_CANCELING;
           progress_group -> hide();
           // safely stop thread!!!!
           //try
             // {
              //EnterCriticalSection(&criticalSection);
              info.canceled = true;
              //LeaveCriticalSection(&criticalSection);
              //}
           //catch(...)
             // {
              //LeaveCriticalSection(&criticalSection);
              //}
           }
     }
}

State* NewScenarioState::idle(void)
{
//printf("NewScenarioState\n");
browse_group->reveal();
if(kb->isPressed(27)) exit(0);
//if(kb->isPressed(GLUT_KEY_LEFT))       info.scenarioProgress -= 0.01f;
//if(kb->isPressed(GLUT_KEY_RIGHT))      info.scenarioProgress += 0.01f;
//if(kb->isPressed(GLUT_KEY_UP))         info.mapProgress -= 0.01f;
//if(kb->isPressed(GLUT_KEY_DOWN))       info.mapProgress += 0.01f;
//if(kb->isPressed(GLUT_KEY_PAGE_UP))    info.texturesProgress -= 0.01f;
//if(kb->isPressed(GLUT_KEY_PAGE_DOWN))  info.texturesProgress += 0.01f;

if(innerState == NEW_SCENARIO_LOADING) { 
	ScenarioCreationState *tmps = new ScenarioCreationState(this,&info,NEWSCENARIO);; 
	tmps->bindTextures(); 
	tmps->createStates();
	this->nextState = tmps; 
}

if(shouldDeleteNextState) this->deleteNextState();

if(nextState == this) {return nextState;}
else {State* tmpState = nextState; this->reset(); return tmpState;}
}

void NewScenarioState::loadTextures(LoadingInfo *li)
{
ssgTexture *t1 = new ssgTexture(li->map_filename);//;"./crissolo_obj.bmp");
ssgTexture *t2 = new ssgTexture("./snow1.bmp");

li->textures[GRASS0_TEXTURE] = t1->getHandle();
li->textures[STONES0_TEXTURE] = t2->getHandle();

// allocate textures in this thread...
GLuint map_textures_numbers[3];
glGenTextures(3, map_textures_numbers);
li->textures[MAP1_TEXTURE] =  map_textures_numbers[0]; 
li->textures[MAP2_TEXTURE] =  map_textures_numbers[1];
li->textures[MAP3_TEXTURE] =  map_textures_numbers[2];

ssgTexture *t3 = new ssgTexture("./housesNormal.bmp");//3
ssgTexture *t4 = new ssgTexture("./housesFocused.bmp");
ssgTexture *t5 = new ssgTexture("./housesClicked.bmp");

li->textures[ICON_BUTTON_BUILDINGS_N] =  t3->getHandle();
li->textures[ICON_BUTTON_BUILDINGS_F] =  t4->getHandle();
li->textures[ICON_BUTTON_BUILDINGS_C] =  t5->getHandle();

ssgTexture *t6 = new ssgTexture("./treeNormal.bmp");
ssgTexture *t7 = new ssgTexture("./treeFocused.bmp");
ssgTexture *t8 = new ssgTexture("./treeClicked.bmp");

li->textures[ICON_BUTTON_TREES_N] =  t6->getHandle();
li->textures[ICON_BUTTON_TREES_F] =  t7->getHandle();
li->textures[ICON_BUTTON_TREES_C] =  t8->getHandle();

ssgTexture *t9  = new ssgTexture("./textureNormal.bmp");
ssgTexture *t10 = new ssgTexture("./textureFocused.bmp");
ssgTexture *t11 = new ssgTexture("./textureClicked.bmp");

li->textures[ICON_BUTTON_TEXTURES_N] =  t9->getHandle();
li->textures[ICON_BUTTON_TEXTURES_F] =  t10->getHandle();
li->textures[ICON_BUTTON_TEXTURES_C] =  t11->getHandle();

ssgTexture *t12  = new ssgTexture("./zoominNormal.bmp");
ssgTexture *t13 = new ssgTexture("./zoominFocused.bmp");
ssgTexture *t14 = new ssgTexture("./zoominClicked.bmp");

li->textures[ICON_BUTTON_ZOOMIN_N] =  t12->getHandle();
li->textures[ICON_BUTTON_ZOOMIN_F] =  t13->getHandle();
li->textures[ICON_BUTTON_ZOOMIN_C] =  t14->getHandle();

ssgTexture *t15  = new ssgTexture("./zoomoutNormal.bmp");
ssgTexture *t16 = new ssgTexture("./zoomoutFocused.bmp");
ssgTexture *t17 = new ssgTexture("./zoomoutClicked.bmp");

li->textures[ICON_BUTTON_ZOOMOUT_N] =  t15->getHandle();
li->textures[ICON_BUTTON_ZOOMOUT_F] =  t16->getHandle();
li->textures[ICON_BUTTON_ZOOMOUT_C] =  t17->getHandle();

ssgTexture *t18  = new ssgTexture("./saveNormal.bmp");
ssgTexture *t19 = new ssgTexture("./saveFocused.bmp");
ssgTexture *t20 = new ssgTexture("./saveClicked.bmp");

li->textures[ICON_BUTTON_SAVE_N] =  t18->getHandle();
li->textures[ICON_BUTTON_SAVE_F] =  t19->getHandle();
li->textures[ICON_BUTTON_SAVE_C] =  t20->getHandle();

ssgTexture *t21  = new ssgTexture("./rotateCWNormal.bmp");
ssgTexture *t22 = new ssgTexture("./rotateCWFocused.bmp");
ssgTexture *t23 = new ssgTexture("./rotateCWClicked.bmp");

li->textures[ICON_BUTTON_ROTATECW_N] =  t21->getHandle();
li->textures[ICON_BUTTON_ROTATECW_F] =  t22->getHandle();
li->textures[ICON_BUTTON_ROTATECW_C] =  t23->getHandle();

ssgTexture *t24  = new ssgTexture("./rotateCCWNormal.bmp");
ssgTexture *t25 = new ssgTexture("./rotateCCWFocused.bmp");
ssgTexture *t26 = new ssgTexture("./rotateCCWClicked.bmp");

li->textures[ICON_BUTTON_ROTATECCW_N] =  t24->getHandle();
li->textures[ICON_BUTTON_ROTATECCW_F] =  t25->getHandle();
li->textures[ICON_BUTTON_ROTATECCW_C] =  t26->getHandle();

ssgTexture *t27  = new ssgTexture("./undoNormal.bmp");
ssgTexture *t28 = new ssgTexture("./undoFocused.bmp");
ssgTexture *t29 = new ssgTexture("./undoClicked.bmp");

li->textures[ICON_BUTTON_UNDO_N] =  t27->getHandle();
li->textures[ICON_BUTTON_UNDO_F] =  t28->getHandle();
li->textures[ICON_BUTTON_UNDO_C] =  t29->getHandle();

ssgTexture *t30  = new ssgTexture("./repeatNormal.bmp");
ssgTexture *t31 = new ssgTexture("./repeatFocused.bmp");
ssgTexture *t32 = new ssgTexture("./repeatClicked.bmp");

li->textures[ICON_BUTTON_REDO_N] =  t30->getHandle();
li->textures[ICON_BUTTON_REDO_F] =  t31->getHandle();
li->textures[ICON_BUTTON_REDO_C] =  t32->getHandle();

ssgTexture *t33  = new ssgTexture("./exitNormal.bmp");
ssgTexture *t34 = new ssgTexture("./exitFocused.bmp");
ssgTexture *t35 = new ssgTexture("./exitClicked.bmp");

li->textures[ICON_BUTTON_EXIT_N] =  t33->getHandle();
li->textures[ICON_BUTTON_EXIT_F] =  t34->getHandle();
li->textures[ICON_BUTTON_EXIT_C] =  t35->getHandle();

li->textures[ICON_BUTTON_EXIT_N] =  t33->getHandle();
li->textures[ICON_BUTTON_EXIT_F] =  t34->getHandle();
li->textures[ICON_BUTTON_EXIT_C] =  t35->getHandle();

ssgTexture *t36  = new ssgTexture("./destroyNormal.bmp");
ssgTexture *t37 = new ssgTexture("./destroyFocused.bmp");
ssgTexture *t38 = new ssgTexture("./destroyClicked.bmp");

li->textures[ICON_BUTTON_BULLDOZER_N] =  t36->getHandle();
li->textures[ICON_BUTTON_BULLDOZER_F] =  t37->getHandle();
li->textures[ICON_BUTTON_BULLDOZER_C] =  t38->getHandle();

ssgTexture *t39  = new ssgTexture("./facilitiesNormal.bmp");
ssgTexture *t40 = new ssgTexture("./facilitiesFocused.bmp");
ssgTexture *t41 = new ssgTexture("./facilitiesClicked.bmp");

li->textures[ICON_BUTTON_FACILITIES_N] =  t39->getHandle();
li->textures[ICON_BUTTON_FACILITIES_F] =  t40->getHandle();
li->textures[ICON_BUTTON_FACILITIES_C] =  t41->getHandle();

ssgTexture *t42  = new ssgTexture("./waypointNormal.bmp");
ssgTexture *t43 = new ssgTexture("./waypointFocused.bmp");
ssgTexture *t44 = new ssgTexture("./waypointClicked.bmp");

li->textures[ICON_BUTTON_WAYPOINTS_N] =  t42->getHandle();
li->textures[ICON_BUTTON_WAYPOINTS_F] =  t43->getHandle();
li->textures[ICON_BUTTON_WAYPOINTS_C] =  t44->getHandle();

ssgTexture *t45  = new ssgTexture("./cameraNormal.bmp");
ssgTexture *t46 = new ssgTexture("./cameraFocused.bmp");
ssgTexture *t47 = new ssgTexture("./cameraClicked.bmp");

li->textures[ICON_BUTTON_MOVIE_N] =  t45->getHandle();
li->textures[ICON_BUTTON_MOVIE_F] =  t46->getHandle();
li->textures[ICON_BUTTON_MOVIE_C] =  t47->getHandle();

readAndLoadLandTextures(li);
readAndLoadObjectsTextures(li);

ssgTexture *t48  = new ssgTexture("./addWaypoint.bmp");
ssgTexture *t49 = new ssgTexture("./deleteWaypoint.bmp");
ssgTexture *t50 = new ssgTexture("./moveWaypoint.bmp");
ssgTexture *t50b = new ssgTexture("./insertWaypoint.bmp");

li->waypointTextures = 4;
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->facilityTextures+0] =  t48->getHandle();
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->facilityTextures+1] =  t49->getHandle();
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->facilityTextures+2] =  t50->getHandle();
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->facilityTextures+3] =  t50b->getHandle();

ssgTexture *t51 = new ssgTexture("./addMovie.bmp");
ssgTexture *t52 = new ssgTexture("./deleteMovie.bmp");
ssgTexture *t53 = new ssgTexture("./moveMovie.bmp");
ssgTexture *t53b = new ssgTexture("./insertMovie.bmp");

li->movieTextures = 4;
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->waypointTextures+li->facilityTextures+0] =  t51->getHandle();
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->waypointTextures+li->facilityTextures+1] =  t52->getHandle();
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->waypointTextures+li->facilityTextures+2] =  t53->getHandle();
li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+li->treeTextures+li->buildingButtonsTextures+li->waypointTextures+li->facilityTextures+3] =  t53b->getHandle();


li->texturesProgress = 1.0f;
}

void NewScenarioState::readAndLoadObjectsTextures(LoadingInfo *li)
{
FILE* f;
ssgTexture* t;

char line[1024];
char path[2050];

int jj = 0;
int k = 0;

if( (f = fopen(BUILDING_TYPES_FILE_NAME,"r")) != NULL)
	{
	while( fscanf(f,"%s",line) != EOF )
		{
		while( line[k] != '.' )
			{
			k++;
			}
		line[k+1] = 'b';
		line[k+2] = 'm';
		line[k+3] = 'p';
		line[k+4] = '\0';
		k = 0;
		//adjustFileName(line);
		ulMakePath(path,TEXTURE_BUTTON_PATH,line);
		t = new ssgTexture(path);		
		li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+jj] = t->getHandle();
		jj+=1;
		}
	li->buildingButtonsTextures = jj;
	fclose(f);
	}
else
	{
	printf("Cannot open %s object file for loading button building textures...\n",BUILDING_TYPES_FILE_NAME);
	}

jj = 0;
if( (f = fopen(TREE_TYPES_FILE_NAME,"r")) != NULL)
	{
	while( fscanf(f,"%s",line) != EOF )
		{
		while( line[k] != '.' )
			{
			k++;
			}
		line[k+1] = 'b';
		line[k+2] = 'm';
		line[k+3] = 'p';
		line[k+4] = '\0';
		k = 0;
		//adjustFileName(line);
		ulMakePath(path,TEXTURE_BUTTON_PATH,line);
		t = new ssgTexture(path);		
		li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+jj+li->buildingButtonsTextures] = t->getHandle();
		jj+=1;
		}
	li->treeTextures = jj;
	fclose(f);
	}
else
	{
	printf("Cannot open %s object file for loading button tree textures...\n",TREE_TYPES_FILE_NAME);
	}

jj = 0;
if( (f = fopen(FACILITY_TYPES_FILE_NAME,"r")) != NULL)
	{
	while( fscanf(f,"%s",line) != EOF )
		{
		while( line[k] != '.' )
			{
			k++;
			}
		line[k+1] = 'b';
		line[k+2] = 'm';
		line[k+3] = 'p';
		line[k+4] = '\0';
		k = 0;
		//adjustFileName(line);
		ulMakePath(path,TEXTURE_BUTTON_PATH,line);
		t = new ssgTexture(path);		
		li->textures[COUNTRYSIDE_TEXTURES+li->landTextures+jj+li->buildingButtonsTextures+li->treeTextures] = t->getHandle();
		jj+=1;
		}
	li->facilityTextures = jj;
	fclose(f);
	}
else
	{
	printf("Cannot open %s facilty file for loading button facility textures...\n",FACILITY_TYPES_FILE_NAME);
	}
 
}

void NewScenarioState::readAndLoadLandTextures(LoadingInfo *li)
{

FILE* f;
ssgTexture *t;
char line[1024];
char path[2050];
bool go = FALSE;
int jj = 0;
int i = 0;

if( (f = fopen(TEXTURE_TYPE_FILE_NAME0,"r")) != NULL)
	{
	while( fscanf(f,"%s",line) != EOF )
		{
		adjustFileName(line);
		ulMakePath(path,TEXTURE_PATH,line);
		t = new ssgTexture(path);		
		li->textures[COUNTRYSIDE_TEXTURES+jj] = t->getHandle();
		
		jj+=1;
		}
	li->landTextures = jj;
	fclose(f);
	}
else
	{
	printf("Cannot open %s textures file...\n",TEXTURE_TYPE_FILE_NAME0);
	}
}

void NewScenarioState::reload()
{
this->browse_group->reveal();
this->shouldDeleteNextState = TRUE;
}

void NewScenarioState::deleteNextState()
{
delete this->nextState;
this->nextState = this;
this->shouldDeleteNextState = FALSE;
}

unsigned int NewScenarioState::loadNewScenario(void *lpParam)
{
// cast to the struct used for intercommunication
LoadingInfo* li = (LoadingInfo*)lpParam;
li->cnt->makeCurrent();
//printf("In loadNewScenario %d\n",&criticalSection);
// create in this separate thread the new state
// The li structure will be modified concurrently, using critical regions (I hope!)
//ScenarioCreationState *scs = new ScenarioCreationState(li->old_s,li,NEWSCENARIO);
// li.state should contain the pointer to the ScenarioCreationState;
//try
   //{
  // EnterCriticalSection(&criticalSection);
   li->completed = true; // new state created!
   //LeaveCriticalSection(&criticalSection);
   //}
//catch(...)
  // {
   //LeaveCriticalSection(&criticalSection);
   //}
return 1;
}

void NewScenarioState::pick_dem ( puObject * p)
{
  NewScenarioState* nss;
  nss = (NewScenarioState*) p->getUserData();

  p -> getValue(nss->dem_file);

  // is really a .DEM file ???
  char ext[4];
  int i = 0;
  bool go = true;

  // default string

  while( go ) 
  {
  if( *(nss->dem_file + i)  == '.')
	{
	ext[0] = *(nss->dem_file+i + 1);
	ext[1] = *(nss->dem_file+i + 2);
	ext[2] = *(nss->dem_file+i + 3);
	ext[3] = '\0';
	go = false;
	}
  else if( *(nss->dem_file + i) == '\0')
	{
	go = false;
	}
  else
	{
	  i++;
	}
  }

  printf("file: %s ext: %s",nss->dem_file,ext);

  if( 1)//(strcmp(ext,"DEM\0") == 0) || (strcmp(ext,"dem\0") == 0) )
	{
    nss->innerState = NEW_SCENARIO_SELECTED;

    strcpy(nss->map_file,nss->dem_file);
	strcpy(nss->tex_file,nss->dem_file);
	strcpy(nss->obj_file,nss->dem_file);
	strcpy(nss->wpn_file,nss->dem_file);
	strcpy(nss->cmv_file,nss->dem_file);
	//printf("\n%s\n",nss->wpn_file);

    *(nss->map_file+i + 0) = '_';
    *(nss->map_file+i + 1) = 'm';
	*(nss->map_file+i + 2) = 'a';
	*(nss->map_file+i + 3) = 'p';
	*(nss->map_file+i + 4) = '.';
	*(nss->map_file+i + 5) = 'b';
	*(nss->map_file+i + 6) = 'm';
	*(nss->map_file+i + 7) = 'p';
	*(nss->map_file+i + 8) = '\0';

	
    *(nss->tex_file+i + 0) = '_';
    *(nss->tex_file+i + 1) = 't';
	*(nss->tex_file+i + 2) = 'e';
	*(nss->tex_file+i + 3) = 'x';
	*(nss->tex_file+i + 4) = '.';
	*(nss->tex_file+i + 5) = 'b';
	*(nss->tex_file+i + 6) = 'm';
	*(nss->tex_file+i + 7) = 'p';
	*(nss->tex_file+i + 8) = '\0';
	
    *(nss->obj_file+i + 0) = '_';
    *(nss->obj_file+i + 1) = 'o';
	*(nss->obj_file+i + 2) = 'b';
	*(nss->obj_file+i + 3) = 'j';
	*(nss->obj_file+i + 4) = '.';
	*(nss->obj_file+i + 5) = 'b';
	*(nss->obj_file+i + 6) = 'm';
	*(nss->obj_file+i + 7) = 'p';
	*(nss->obj_file+i + 8) = '\0';

    *(nss->wpn_file+i + 0) = '.';
    *(nss->wpn_file+i + 1) = 'w';
	*(nss->wpn_file+i + 2) = 'p';
	*(nss->wpn_file+i + 3) = 'n';
	*(nss->wpn_file+i + 4) = '\0';

    *(nss->cmv_file+i + 0) = '.';
    *(nss->cmv_file+i + 1) = 'c';
	*(nss->cmv_file+i + 2) = 'm';
	*(nss->cmv_file+i + 3) = 'v';
	*(nss->cmv_file+i + 4) = '\0';

	//printf("\n%s\n",nss->wpn_file);
	}
  else
	{
	strcpy(nss->dem_file,"Not a .DEM file... Choose Another one!!!\0");
	}
     
 //printf("dem: %s\nmap: %s\ntex: %s\nobj: %s\n",nss->dem_file,nss->map_file,nss->tex_file,nss->obj_file);
  puDeleteObject ( p ) ;
  p = 0 ;
}

void NewScenarioState::pick_map ( puObject * p)
{
  NewScenarioState* nss;
  nss = (NewScenarioState*) p->getUserData();

  p -> getValue(nss->map_file);

  //printf("%s\n",filename);
  puDeleteObject ( p ) ;
  p = 0 ;
}

void NewScenarioState::pick_tex ( puObject * p)
{
  NewScenarioState* nss;
  nss = (NewScenarioState*) p->getUserData();

  p -> getValue(nss->tex_file);

  //printf("%s\n",filename);
  puDeleteObject ( p ) ;
  p = 0 ;
}

void NewScenarioState::pick_obj ( puObject * p)
{
  NewScenarioState* nss;
  nss = (NewScenarioState*) p->getUserData();

  p -> getValue(nss->obj_file);

  //printf("%s\n",filename);
  puDeleteObject ( p ) ;
  p = 0 ;
}

void NewScenarioState::browse_dem ( puObject * p)
{
  int h = (float)glutGet ( (GLenum) GLUT_WINDOW_HEIGHT ) ;
  int w = (float)glutGet ( (GLenum) GLUT_WINDOW_WIDTH  ) ;

  puOneShot *pos = (puOneShot*)p;
  NewScenarioState* nss = (NewScenarioState*) pos->getUserData();
  puaFileSelector *pfs =  new puaFileSelector ( 0.11f * w, 0.21f * h, 0.77f * w, 0.5f * h, 2, START_DIRECTORY , "Select the .DEM file" ) ;
  pfs -> setCallback ( pick_dem ) ;
  pfs -> setUserData( nss );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_FOREGROUND, COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_BACKGROUND, COLOR_RED );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_HIGHLIGHT,  COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_HIGHLIGHT,   COLOR_ICE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_FOREGROUND,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_BACKGROUND,  COLOR_ICE );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_LABEL    ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LEGEND  ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LABEL    , COLOR_WHITE );
}

void NewScenarioState::browse_map ( puObject * p)
{
  int h = (float)glutGet ( (GLenum) GLUT_WINDOW_HEIGHT ) ;
  int w = (float)glutGet ( (GLenum) GLUT_WINDOW_WIDTH  ) ;

  puOneShot *pos = (puOneShot*)p;
  NewScenarioState* nss = (NewScenarioState*) pos->getUserData();
  puaFileSelector *pfs =  new puaFileSelector ( 0.11f * w, 0.21f * h, 0.77f * w, 0.5f * h, 2, START_DIRECTORY , "Select the .BMP map file" ) ;
  pfs -> setCallback ( pick_map );
  pfs -> setUserData ( nss );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_FOREGROUND, COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_BACKGROUND, COLOR_RED );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_HIGHLIGHT,  COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_HIGHLIGHT,   COLOR_ICE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_FOREGROUND,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_BACKGROUND,  COLOR_ICE );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_LABEL    ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LEGEND  ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LABEL    , COLOR_WHITE );
}

void NewScenarioState::browse_tex ( puObject * p)
{
  int h = (float)glutGet ( (GLenum) GLUT_WINDOW_HEIGHT ) ;
  int w = (float)glutGet ( (GLenum) GLUT_WINDOW_WIDTH  ) ;

  puOneShot *pos = (puOneShot*)p;
  NewScenarioState* nss = (NewScenarioState*) pos->getUserData();
  puaFileSelector *pfs =  new puaFileSelector ( 0.11f * w, 0.21f * h, 0.77f * w, 0.5f * h, 2, START_DIRECTORY , "Select the .BMP texture file" ) ;
  pfs -> setCallback ( pick_tex );
  pfs -> setUserData ( nss );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_FOREGROUND, COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_BACKGROUND, COLOR_RED );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_HIGHLIGHT,  COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_HIGHLIGHT,   COLOR_ICE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_FOREGROUND,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_BACKGROUND,  COLOR_ICE );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_LABEL    ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LEGEND  ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LABEL    , COLOR_WHITE );
}

void NewScenarioState::browse_obj ( puObject * p)
{
  int h = (float)glutGet ( (GLenum) GLUT_WINDOW_HEIGHT ) ;
  int w = (float)glutGet ( (GLenum) GLUT_WINDOW_WIDTH  ) ;

  puOneShot *pos = (puOneShot*)p;
  NewScenarioState* nss = (NewScenarioState*) pos->getUserData();
  puaFileSelector *pfs =  new puaFileSelector ( 0.11f * w, 0.21f * h, 0.77f * w, 0.5f * h, 2, START_DIRECTORY , "Select the .BMP 3D objects file" ) ;
  pfs -> setCallback ( pick_obj );
  pfs -> setUserData ( nss );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_FOREGROUND, COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_BACKGROUND, COLOR_RED );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_HIGHLIGHT,  COLOR_SUNBURST );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_HIGHLIGHT,   COLOR_ICE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_FOREGROUND,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_INPUT, PUCOL_BACKGROUND,  COLOR_ICE );
  pfs -> setChildColour( PUCLASS_OBJECT, PUCOL_LABEL    ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LEGEND  ,  COLOR_WHITE );
  pfs -> setChildColour( PUCLASS_ONESHOT, PUCOL_LABEL    , COLOR_WHITE );
}

